package net.unix8.thread;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.jfinal.kit.PathKit;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import net.unix8.ftp.easyFTP;
import net.unix8.server.ServerHandler;
import net.unix8.share.NetworkShare;
import net.unix8.tool.Tools;

public class DownloadFile extends Thread{

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	private String host;
	private String fileName;

	private String saveDirName;
	//private String saveFileName;
	private ChannelId channel;
	private int id;
	
	public DownloadFile(ChannelId channel,int id, String host, String name, String passwd,
			String workPath, String fileName, String saveDirName/*, String saveFileName*/){
		this.host = host;
		this.fileName = fileName;
		String pathString = PathKit.getWebRootPath() + "/data/" + host+"/";
		File file =new File(pathString);    
		if  (!file.exists()  && !file.isDirectory())      
		{       
			file.mkdir();    
		} 
		this.saveDirName = pathString;//(saveDirName ==  null ? "E:\\pub\\":saveDirName);
		//this.saveFileName = saveFileName;	
		this.channel = channel;
		this.id = id;
	}

	@Override
	public void run() {
		Boolean status = false;
		//本地搜索
		List<String> lstFileNames = Tools.tree(saveDirName);//先在本地找
		if(lstFileNames.size() != 0){
			String []names = new String[lstFileNames.size()];
			lstFileNames.toArray(names);
			String tFileName = fileName;
			tFileName = Tools.findDataName(tFileName, names);
			if(tFileName != null){
				status = true;
				System.out.println("Locate Find the file:"+saveDirName+tFileName);			
			}else {
				System.out.println("Cannot Locate Find the file:"+saveDirName+tFileName);			
				status = false;
			}
			fileName = tFileName;
		}
		
		//远程搜索
		if(false){
			easyFTP ftp = ServerHandler.getFtp(host);//获取ftp
			try {			
				if((ftp != null) && (ftp.getFtpClient().isAvailable() && ftp.getFtpClient().isConnected())){
					System.out.println("该FTP链接可以使用："+host);	
				}else{
					System.out.println("该FTP链接不可以使用："+host);
					if(ftp != null)ftp.disconnect();
					ftp = new easyFTP();
					System.out.println("创建新的FTP链接："+host);
					ftp.getFtpClient().setRemoteVerificationEnabled(false);
					ftp.getFtpClient().enterLocalPassiveMode();
					ftp.getFtpClient().setControlEncoding("UTF-8");
					ftp.connect(host,"ftpuser","123456");
					ServerHandler.addFtp(host,ftp);
				}
			
				boolean status1 = ftp.setWorkingDirectory("/var/ftp/pub/");
				if(status1){
					String []names = ftp.listName();
					//System.out.println("有文件个数:"+names.length+"  " + fileName);
					fileName = Tools.findDataName(fileName, names);
					if(fileName != null){
						//System.out.println("Remote Find the file:"+saveDirName+fileName);			
						status = true;
						ftp.downloadFile(fileName,saveDirName+fileName);
						//ftp.deleteFile(fileName);//?????????????++++++++++++++++++++++++++++
					}else {
						status = false;
						//System.out.println(" Remote Cannot Find the file:"+saveDirName+fileName);	
					}
				}
				//ftp.disconnect();
			} catch (Exception e) {
				status = false;
				ftp.disconnect();			
				// TODO Auto-generated catch block
				e.printStackTrace();
				fileName = "Can not connect to host:"+host;
			}
		}


		JSONObject studentJSONObject = new JSONObject();  
		try {  
			studentJSONObject.put("host", host);
			studentJSONObject.put("id", id);  
			studentJSONObject.put("cmd", "data"); 
			studentJSONObject.put("status", status);  
			if((fileName == null) || (status ==false)){
				fileName = "Can not find the file";
			}
			studentJSONObject.put("data", fileName);  
		} catch (JSONException e) {  
			e.printStackTrace();  
		}  


		Channel remoteChannel = NetworkShare.clientGroup.find(channel);
		if(remoteChannel != null){
			final ByteBuf firstMessage;
			firstMessage = Unpooled.buffer(100);
			firstMessage.writeCharSequence(studentJSONObject.toString(), Charset.forName("UTF-8"));
			remoteChannel.writeAndFlush(firstMessage);
		}
	}
}